package main

import (
	"crypto/ecdsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
)

func readPublicKey() (*ecdsa.PublicKey, error) {
	block, _ := pem.Decode([]byte(`-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKG06KBmsmZe1ni2afVMx5NXo0vT0
op13IOeI0qgPLbJ/prfzhw1QsIut2RpCHwgOMDA/N2piqjnK1UHQEZcD1g==
-----END PUBLIC KEY-----`))
	pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	return pubKey.(*ecdsa.PublicKey), nil
}

func main() {
	pubKey, _ := readPublicKey()

	// 要解密的 Token 字符串
	tokenString := "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwiaWF0IjoxNjgwOTIxOTc5LCJuYW1lIjoiQWxpY2UifQ.x3aGGQMoLlFI_E9usyDNnE_t6yEuRkHh848fQFVl78qvOhFM1KcLkBdYU_eBQGynm9gp9uCAdYtLNZcYjP2NZA"

	// 解密 Token
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return pubKey, nil
	})
	if err != nil {
		fmt.Println("Error parsing JWT token:", err)
		return
	}

	// 验证 Token
	if !token.Valid {
		fmt.Println("Invalid JWT token")
		return
	}

	// 获取 Token 的声明（payload）
	claims := token.Claims.(jwt.MapClaims)
	fmt.Println("Name:", claims["name"])
	fmt.Println("Is admin:", claims["admin"])
	fmt.Println("Issued at:", claims["iat"])
}
